package com.nus.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.nus.beans.Leave;
import com.nus.beans.LeaveStatus;
import com.nus.beans.User;
import com.nus.database.LeavesDBManager;
import com.nus.database.UserDBManager;
import com.nus.services.ConversionService;
import org.apache.log4j.Logger;

public class ApplyLeaveServlet extends AbstractServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String errorMessage = "";
        User user = (User) request.getSession().getAttribute("user");
        ConversionService conversionService = new ConversionService();
        if (user.getRemainingLeaves() > 0) {
            int yearFrom = Integer.parseInt(request.getParameter("yearFrom"));
            int monthFrom = Integer.parseInt(request.getParameter("monthFrom"));
            int dayFrom = Integer.parseInt(request.getParameter("dayFrom"));


            Date date = conversionService.getDate(yearFrom, monthFrom, dayFrom);
            if (date == null) {
                errorMessage = "Invalid leave date.";
            } else {
                Leave leave = new Leave(user.getUserId(), date);
                LeaveStatus leaveStatus = conversionService.getLeaveStatusByUserType(user.getUserType());
                leave.setStatus(leaveStatus);

                Connection connection = getUserDatabaseConnection(request);
                LeavesDBManager leavesDBManager = new LeavesDBManager(connection);
                UserDBManager userDBManager = new UserDBManager(connection);
                if (leavesDBManager.isLeaveApplicable(leave)) {
                    leavesDBManager.applyLeave(leave);
                    user = userDBManager.getUser(user.getLoginName());
                    request.getSession().setAttribute("user", user);
                    errorMessage = "Leave request has been submitted.";
                } else {
                    errorMessage = "You have already applied a leave for this date.";
                }
                leavesDBManager.close();
                userDBManager.close();
            }
        } else {
            errorMessage = "Leave request has been rejected. You have no leaves left.";
        }

        request.setAttribute("ERROR_MESSAGE", errorMessage);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/apply_leave.jsp");
        requestDispatcher.forward(request, response);
    }
}
